import React from 'react';
import { Button } from 'antd';
import qs from 'querystring';
import ProxyDemo from './ProxyDemo';
import api from '../../../api';

export default class Fetch extends React.Component{
  constructor(){
    super();
    this.state={
      banner: [],
      data: ''
    }
  }
  getData = () => {
    /**
     * fetch基于promise
     * get请求
    */
    fetch("http://iwenwiki.com/api/blueberrypai/getIndexBanner.php")
    .then(res => {
      // response响应对象
      return res.json();
    })
    .then( data => {
      // 拿到return数据
      console.log(data)
      this.setState({
        banner: data.banner
      })
    })
  }
  postData = () => {
    /**
     * fetch基于promise
     * post请求
    */
    fetch("http://iwenwiki.com/api/blueberrypai/login.php",{
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/json,text/plain,*/*"
      },
      body: qs.stringify({
        user_id: "iwen@qq.com",
        password: "iwen123",
        verification_code: "crfvw"
      })
      // body: "user_id=iwen@qq.com&password=iwen123&verification_code=crfvw"
    })
    .then(res => {
      // response响应对象
      return res.json();
    })
    .then( data => {
      // 拿到return数据
      console.log(data)
      this.setState({
        data: data.msg
      })
    })
  }
  // 调用封装的get函数
  getChengpin = () => {
    api.getChengpin()
    .then(res => res.json())
    .then(data => {
      console.log(data);
    })
  }
  // 调用封装的post请求
  getLogin = () => {
    api.getLogin({
      user_id: "iwen@qq.com",
      password: "iwen123",
      verification_code: "crfvw"
    })
    .then(res => res.json())
    .then(data => {
      console.log(data);
    })
  }
  render(){
    const {
      banner,
      data
    } = this.state;
    return(
      <div>
        <Button onClick={ this.getData }>get方式请求获取数据</Button>
        <ul>
          {
            banner ? banner.map((item, index) => {
              return(
                <li key={index}>
                  <h5>{item.title}</h5>
                  <text>{item.content}</text>
                  <img style={{width: "100px",height: "50px"}} src={item.img} alt=""/>
                </li>
              )
            })
            :
            ''
          }
        </ul>
        <Button onClick={ this.postData }>post方式请求获取数据</Button>
        <p>{data ? data : ''}</p>
        <ProxyDemo />
        <Button onClick={this.getChengpin}>调用封装的get请求</Button>
        <Button onClick={this.getLogin}>调用封装的post请求</Button>
      </div>
    )
  }
}